﻿using System;
using System.Collections.Generic;
using System.Text;
using Microsoft.Win32;

namespace Umbrella.Whs
{
    public static class UmbrellaRegistry
    {
        private static readonly string RegistryHklmPath = Properties.Constants.UmbrellaRegistryPath;
        private const string InstanceIdName = "InstanceId";
        private static readonly Guid GlobalMutexGuid = new Guid("{D9712F9F-1811-4112-9E86-30D3A71F840D}");

        private static Guid _instanceGuid = Guid.Empty;

        public static RegistryKey OpenKey()
        {
            var key = Registry.LocalMachine.OpenSubKey(RegistryHklmPath, true);

            if (key == null)
            {
                key = Registry.LocalMachine.CreateSubKey(RegistryHklmPath);
            }

            return key;
        }

        public static Guid GetInstanceId()
        {
            // already known?
            if (_instanceGuid != Guid.Empty)
                return _instanceGuid;

            // open key
            var key = OpenKey();

            // get value
            var id = key.GetValue(InstanceIdName) as string;

            if (string.IsNullOrEmpty(id))
            {
                using (new GlobalMutex(GlobalMutexGuid).ForceLock)
                {
                    id = key.GetValue(InstanceIdName) as string;

                    if (string.IsNullOrEmpty(id))
                    {
                        _instanceGuid = Guid.NewGuid();
                        id = _instanceGuid.ToString();

                        key.SetValue(InstanceIdName, id);

                        return GetInstanceId();
                    }
                }
            }

            // got value
            _instanceGuid = new Guid(id);

            return _instanceGuid;
        }
    }
}